import os
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from PIL import Image

import random
if tf.__version__ < '1.4.0':
    raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')
#分类冻结的权重文件
INCPETION_MODEL_FILE = 'res/models/inception_v4.pb'
#定义一个全局图
inception_graph = tf.Graph()
'''初始化，将分类网络权重进行预加载'''
def init():
    with inception_graph.as_default():
        inception_graph_def = tf.GraphDef()
        with tf.gfile.GFile(INCPETION_MODEL_FILE, 'rb') as fid:
            serialized_graph = fid.read()
            inception_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(inception_graph_def, name='')
'''分类函数
    image:输入图片全路径
    return：概率最高的分类及其概率'''
def classification(image):
    if not tf.gfile.Exists(image):
        tf.logging.fatal('File does not exist %s', image)
    image_data = tf.gfile.FastGFile(image, 'rb').read()
    with tf.Session(graph=inception_graph) as sess:
        softmax_tensor = sess.graph.get_tensor_by_name('output:0')
        predictions = sess.run(softmax_tensor,
                               {'input:0': image_data})
        predictions = np.squeeze(predictions)
        #print(predictions.argsort())
        #输出为图片概率最高的分类及其概率
        return predictions.argsort()[763], predictions[predictions.argsort()[763]]

